<template>
  <div 
    class="user-avatar" 
    :class="avatarClass"
    @click="handleClick"
  >
    <!-- 头像图片 -->
    <div class="avatar-image">
      <img
        v-if="finalAvatarUrl"
        :src="finalAvatarUrl"
        :alt="alt"
        @load="handleImageLoad"
        @error="handleImageError"
        :loading="lazy ? 'lazy' : 'eager'"
      />
      <div v-else class="avatar-placeholder">
        <el-icon :size="placeholderIconSize">
          <Avatar />
        </el-icon>
      </div>
    </div>
    
    <!-- 在线状态指示器 -->
    <div 
      v-if="showOnlineStatus && isOnline !== null" 
      class="online-indicator"
      :class="{ active: isOnline }"
    ></div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <el-icon class="is-loading" :size="loadingIconSize">
        <Loading />
      </el-icon>
    </div>
    
    <!-- 角标 -->
    <div v-if="badge" class="avatar-badge">
      <el-badge 
        :value="badge" 
        :max="badgeMax"
        :hidden="!badge"
        :type="badgeType"
      >
        <span></span>
      </el-badge>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { Avatar, Loading } from '@element-plus/icons-vue'
import { buildAvatarUrl } from '@/api/avatar'
import { useUserStore } from '@/stores/user'

const props = defineProps({
  // 用户ID
  userId: {
    type: [String, Number],
    default: null
  },
  // 头像URL
  avatarUrl: {
    type: String,
    default: ''
  },
  // 用户名
  username: {
    type: String,
    default: ''
  },
  // 昵称
  nickname: {
    type: String,
    default: ''
  },
  // 尺寸大小
  size: {
    type: String,
    default: 'medium',
    validator: (value) => ['mini', 'small', 'medium', 'large', 'extra-large'].includes(value)
  },
  // 是否显示在线状态
  showOnlineStatus: {
    type: Boolean,
    default: false
  },
  // 在线状态
  isOnline: {
    type: Boolean,
    default: false
  },
  // 是否可点击
  clickable: {
    type: Boolean,
    default: false
  },
  // 是否懒加载
  lazy: {
    type: Boolean,
    default: true
  },
  // alt文本
  alt: {
    type: String,
    default: '用户头像'
  },
  // 角标内容
  badge: {
    type: [String, Number],
    default: null
  },
  // 角标最大值
  badgeMax: {
    type: Number,
    default: 99
  },
  // 角标类型
  badgeType: {
    type: String,
    default: 'danger'
  }
})

const emit = defineEmits(['click', 'load-error', 'load-success'])

const userStore = useUserStore()

// 响应式数据
const currentAvatarUrl = ref('')
const loading = ref(false)
const error = ref(false)
const imageLoaded = ref(false)

// 计算属性
const finalAvatarUrl = computed(() => {
  // 如果有传入的头像URL，直接使用
  if (props.avatarUrl && props.avatarUrl !== '') {
    // 如果是完整的URL，直接返回
    if (props.avatarUrl.startsWith('http')) {
      return props.avatarUrl
    }
    // 如果是相对路径，使用buildAvatarUrl处理
    const builtUrl = buildAvatarUrl(props.avatarUrl)
    return builtUrl
  }
  
  // 如果有当前设置的头像URL
  if (currentAvatarUrl.value && currentAvatarUrl.value !== '') {
    const builtUrl = buildAvatarUrl(currentAvatarUrl.value)
    return builtUrl
  }
  
  // 否则使用默认头像
  return '/default-avatar.svg'
})

const displayName = computed(() => {
  return props.nickname || props.username || '用户'
})

const avatarClass = computed(() => [
  'user-avatar',
  `user-avatar--${props.size}`,
  {
    'user-avatar--clickable': props.clickable,
    'user-avatar--loading': loading.value,
    'user-avatar--error': error.value
  }
])

const placeholderIconSize = computed(() => {
  const sizeMap = {
    mini: 12,
    small: 16,
    medium: 20,
    large: 24,
    'extra-large': 32
  }
  return sizeMap[props.size] || 20
})

const loadingIconSize = computed(() => {
  const sizeMap = {
    mini: 10,
    small: 12,
    medium: 16,
    large: 20,
    'extra-large': 24
  }
  return sizeMap[props.size] || 16
})

// 初始化头像URL
const initAvatarUrl = async () => {
  loading.value = true
  error.value = false
  
  console.log('UserAvatar初始化 - props:', {
    userId: props.userId,
    avatarUrl: props.avatarUrl,
    username: props.username,
    nickname: props.nickname
  })
  
  try {
    // 优先使用传入的头像URL
    if (props.avatarUrl) {
      currentAvatarUrl.value = props.avatarUrl
      console.log('初始化：使用传入的头像URL:', props.avatarUrl)
      console.log('设置currentAvatarUrl为:', currentAvatarUrl.value)
      loading.value = false // 直接设置为false，不需要异步等待
      return
    }
    
    // 如果是当前用户，从store获取
    if (props.userId === userStore.userId && userStore.userInfo?.avatar) {
      currentAvatarUrl.value = userStore.userInfo.avatar
      console.log('初始化：从用户store获取头像:', userStore.userInfo.avatar)
      loading.value = false
      return
    }
    
    // 如果有用户ID，异步获取头像
    if (props.userId) {
      console.log('初始化：尝试异步获取用户头像，userId:', props.userId)
      const avatarUrl = await userStore.fetchUserAvatar(props.userId)
      console.log('初始化：异步获取到的头像URL:', avatarUrl)
      if (avatarUrl && avatarUrl !== '/default-avatar.svg') {
        currentAvatarUrl.value = avatarUrl
        console.log('初始化：设置异步获取的头像:', avatarUrl)
        loading.value = false
        return
      }
    }
    
    // 使用默认头像
    console.log('初始化：使用默认头像')
    currentAvatarUrl.value = '/default-avatar.svg'
    
  } catch (error) {
    console.warn('初始化头像失败:', error)
    currentAvatarUrl.value = '/default-avatar.svg'
    error.value = true
  } finally {
    loading.value = false
  }
}

// 处理头像点击
const handleClick = (event) => {
  if (props.clickable) {
    emit('click', {
      userId: props.userId,
      username: props.username,
      nickname: props.nickname,
      event
    })
  }
}

// 处理图片加载成功
const handleImageLoad = (event) => {
  console.log('头像图片加载成功:', {
    src: event.target?.src,
    naturalWidth: event.target?.naturalWidth,
    naturalHeight: event.target?.naturalHeight
  })
  
  imageLoaded.value = true
  loading.value = false
  error.value = false
  emit('load-success')
}

// 处理图片加载错误
const handleImageError = (event) => {
  console.warn('头像图片加载失败:', event.target?.src)
  
  if (currentAvatarUrl.value !== '/default-avatar.svg') {
    console.log('切换到默认头像')
    currentAvatarUrl.value = '/default-avatar.svg'
    error.value = true
    emit('load-error')
  }
}

// 监听props变化
watch(() => [props.avatarUrl, props.userId], initAvatarUrl, { immediate: false })

// 组件挂载时初始化
onMounted(() => {
  initAvatarUrl()
})
</script>

<style lang="scss" scoped>
.user-avatar {
  position: relative;
  display: inline-block;
  flex-shrink: 0;
  
  // 不同尺寸
  &--mini {
    width: 24px;
    height: 24px;
  }
  
  &--small {
    width: 32px;
    height: 32px;
  }
  
  &--medium {
    width: 40px;
    height: 40px;
  }
  
  &--large {
    width: 56px;
    height: 56px;
  }
  
  &--extra-large {
    width: 80px;
    height: 80px;
  }
  
  // 不同形状
  &--circle .avatar-image {
    border-radius: 50%;
  }
  
  &--square .avatar-image {
    border-radius: $border-radius;
  }
  
  // 可点击状态
  &--clickable {
    cursor: pointer;
    transition: $transition-fast;
    
    &:hover {
      transform: scale(1.05);
    }
  }
  
  // 加载状态
  &--loading {
    .avatar-image {
      opacity: 0.6;
    }
  }
}

.avatar-image {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: $bg-gray;
  border: 1px solid $border-light;
  border-radius: 50%;
  transition: $transition-fast;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
    opacity: 1;
  }
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: $text-gray;
  background: $bg-light;
}

.online-indicator {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 25%;
  height: 25%;
  min-width: 8px;
  min-height: 8px;
  max-width: 12px;
  max-height: 12px;
  background: $text-gray;
  border: 2px solid $text-white;
  border-radius: 50%;
  transition: $transition-fast;
  
  &.active {
    background: $success-color;
  }
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: inherit;
}

.avatar-badge {
  position: absolute;
  top: -2px;
  right: -2px;
  
  :deep(.el-badge__content) {
    border: 1px solid $text-white;
  }
}

// 悬停效果
.user-avatar--clickable:hover {
  .avatar-image {
    border-color: $primary-color;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .user-avatar {
    // 移动端稍微减小尺寸
    &--large {
      width: 48px;
      height: 48px;
    }
    
    &--extra-large {
      width: 64px;
      height: 64px;
    }
  }
}
</style> 